//
//  WTMNetworkTool.m
//  OptimumCarCharge
//
//  Created by WTM on 16/11/18.
//  Copyright © 2016年 童巍. All rights reserved.
//

#import "WTMNetworkTool.h"
#import "Tool.h"

@implementation WTMNetworkTool


+ (instancetype)sharedNetworkTool{
    
    static WTMNetworkTool * _instancetype = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *baseURL = [NSURL URLWithString:@"http://112.74.44.166:8081"];
//        NSURL *baseURL = [NSURL URLWithString:@"http://cw.yunchuangh.com:4601"];
        _instancetype = [[WTMNetworkTool alloc] initWithBaseURL:baseURL];
        _instancetype.requestSerializer = [AFJSONRequestSerializer serializer];
        CGFloat version = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (version >= 10) {
//             [_instancetype.requestSerializer setValue:@"ios/10.1/zhudongchongwei/1.0/en-rUS" forHTTPHeaderField:@"User-Agent"];
            [_instancetype.requestSerializer setValue:@"ios10" forHTTPHeaderField:@"User-Agent"];
        }else{
            [_instancetype.requestSerializer setValue:@"ios9" forHTTPHeaderField:@"User-Agent"];
        
        }
        
       
        _instancetype.requestSerializer.timeoutInterval = 15.0f;
        _instancetype.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html" ,nil];
    });
    return _instancetype;
}


- (void)requestWithUrlstring:(NSString *)urlstr method:(NSString *)method parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError * _Nonnull))failure{
    NSLog(@"paramet is %@",parameters);
    
    
    if (NetWorkStatus == AFNetworkReachabilityStatusNotReachable){
        UIAlertView* alerView=[[UIAlertView alloc]initWithTitle:@"未连接到网络" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerView show];
        return;
    }
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];
    for (NSHTTPCookie *cookie in cookies) {
        if (cookie.version == 0 && [cookie.name isEqualToString:@"SessionKey"]) {
            [self.requestSerializer setValue:[NSString stringWithFormat:@"SessionKey=%@",cookie.value] forHTTPHeaderField:@"Cookie"];
        }
    }
    NSLog(@"cookies is %@",cookies);
    NSLog(@"headerfielf is %@",self.requestSerializer.HTTPRequestHeaders);
//    if ([method isEqualToString:@"GET"]) {
//        
//        [self GET:urlstr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            if (success) {
//                success(responseObject);
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            if (failure) {
//                failure(error);
//            }
//        }];
//    }
//    
//    if ([method isEqualToString:@"POST"]) {
        [self POST:urlstr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dictionary = (NSDictionary *)responseObject;
            if ([[dictionary objectForKey:@"status"]integerValue] == 10019) {
                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                UIViewController *loginVc =   [sb instantiateViewControllerWithIdentifier:@"loginID"];
                [UIApplication sharedApplication].keyWindow.rootViewController = loginVc;
                [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
                [[NSUserDefaults standardUserDefaults] setValue:@(NO) forKey:@"LOGINSTATE"];
                [[NSUserDefaults standardUserDefaults]synchronize];
                [Tool errorWithMsg:[dictionary objectForKey:@"resultMsg"]];
            }else{
                if (success) {
                    success(responseObject);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
//    }
    
}


+ (NSDate *)getInternetDate

{
//    WTMNetworkTool * network = [[WTMNetworkTool alloc]initWithBaseURL:[NSURL URLWithString:@"http://m.baidu.com"]];
//    
//    
//    
//    
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    NSString *urlString = @"http://www.ntsc.ac.cn";
    
//    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
    // 实例化NSMutableURLRequest，并进行参数配置
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    [request setURL:[NSURL URLWithString: urlString]];
    
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    
    [request setTimeoutInterval: 2];
    
    [request setHTTPShouldHandleCookies:FALSE];
    
    [request setHTTPMethod:@"POST"];
    
    NSError *error = nil;
    
    NSHTTPURLResponse *response;

    [NSURLConnection sendSynchronousRequest:request
     
                          returningResponse:&response error:&error];
    
    
    
    // 处理返回的数据
    
    //    NSString *strReturn = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    if (error) {
        return [NSDate date];
    }
    
    NSLog(@"response is %@",response);
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    
    date = [date substringFromIndex:5];
    
    date = [date substringToIndex:[date length]-4];
    
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    return netDate;
    
}


@end
